package com.jet.core.config.feign;

import com.jet.core.exception.CustomException;
import com.jet.core.result.ResultCode;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.charset.Charset;

/**
 * @author dcl
 * @since 2024/5/7 11:47
 */
@Slf4j
public class FeignErrorDecoder implements ErrorDecoder {

    @Override
    public Exception decode(String s, Response response) {
        log.error("feign client error,response is {}:", response.body());
        try {
            if (response.body() != null) {
                String body = Util.toString(response.body().asReader(Charset.defaultCharset()));
                return new CustomException(ResultCode.SERVICE_ERROR.getCode(), ResultCode.SERVICE_ERROR.getMsg(), body);
            }
        } catch (IOException e) {
            log.error("feign client error,response is {}:", response);
            e.printStackTrace();
        }
        return new CustomException(ResultCode.SERVICE_ERROR);
    }
}
